package com.zhy.baselibrary.view;


import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {
    private int spacing;

    public ItemOffsetDecoration(int spacing) {
        this.spacing = spacing;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view);
        int spanCount = ((GridLayoutManager) parent.getLayoutManager()).getSpanCount();
        int itemCount = parent.getAdapter().getItemCount();

        int column = position % spanCount;
        // 第一行
        if (position < spanCount) {
            outRect.top = spacing;
        }
        if (column == 0) {
            outRect.left = spacing;
            outRect.right = spacing / 2;
        } else if (column == spanCount - 1) {
            outRect.right = spacing;
            outRect.left = spacing / 2;
        } else {
            outRect.left = spacing / 2;
            outRect.right = spacing / 2;
            outRect.top = spacing;
        }

        // 最后一行
        if (position >= itemCount - spanCount) {
            outRect.bottom = spacing;
        }
    }
}
